﻿using System;
using System.Reflection;
using System.IO;

namespace Outcoder.Reflection
{
	/* Original source from: http://www.williame.be/blog/post/Detect-if-an-assembly-is-a-managed-assembly.aspx */

	/// <summary>
	/// Returns information about an assembly without loading it into the appdomain.
	/// </summary>
	public class AssemblyFile
	{
       /// <summary>
        /// PE Header starts @ 0x3C (60). Its a 4 byte header.
        /// </summary>
        const long peHeaderStart = 0x3C;

        uint peHeader;
        uint peHeaderSignature;
        ushort machine;
        ushort sections;
        uint timestamp;
        uint pSymbolTable;
        uint noOfSymbol;
        ushort optionalHeaderSize;
        ushort characteristics;
        ushort dataDictionaryStart;
        uint[] dataDictionaryRva;
        uint[] dataDictionarySize;
		readonly string fileName;
        AssemblyName name;

		public AssemblyFile(string fileName)
        {
			ArgumentValidator.AssertNotNull(fileName, "fileName");
            this.fileName = Path.GetFullPath(fileName);
        }

        void GetHeaders()
        {
            dataDictionaryRva = new uint[16];
            dataDictionarySize = new uint[16];

            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                BinaryReader reader = new BinaryReader(fileStream);
                //PE Header starts @ 0x3C (60). Its a 4 byte header.
                fileStream.Position = peHeaderStart;
                peHeader = reader.ReadUInt32();

                //Moving to PE Header start location...
                fileStream.Position = peHeader;
                peHeaderSignature = reader.ReadUInt32();

                //We can also show all these value, but we will be       
                //limiting to the CLI header test.
                machine = reader.ReadUInt16();
                sections = reader.ReadUInt16();
                timestamp = reader.ReadUInt32();
                pSymbolTable = reader.ReadUInt32();
                noOfSymbol = reader.ReadUInt32();
                optionalHeaderSize = reader.ReadUInt16();
                characteristics = reader.ReadUInt16();

                /*
                Now we are at the end of the PE Header and from here, the
                PE Optional Headers starts...
                To go directly to the datadictionary, we'll increase the      
                stream’s current position to with 96 (0x60). 96 because,
                28 for Standard fields
                68 for NT-specific fields
                From here DataDictionary starts...and its of total 128 bytes. DataDictionay has 16 directories in total,
                doing simple maths 128/16 = 8.
                So each directory is of 8 bytes.
                In this 8 bytes, 4 bytes is of RVA and 4 bytes of Size.

                btw, the 15th directory consist of CLR header! if its 0, its not a CLR file :)
                */

                dataDictionaryStart = Convert.ToUInt16(Convert.ToUInt16(fileStream.Position) + 0x60);
                fileStream.Position = dataDictionaryStart;

                for (int i = 0; i < 15; i++)
                {
                    dataDictionaryRva[i] = reader.ReadUInt32();
                    dataDictionarySize[i] = reader.ReadUInt32();
                }
                fileStream.Close();
            }
        }

		bool? managed;

        public bool Managed
        {
            get
            {
                try
                {
                    if (!managed.HasValue)
                    {
                        GetHeaders();
                    }
                    managed = dataDictionaryRva[14] != 0;
                }
                catch (Exception)
                {
                	managed = false;
                	// when an error occurs return false.
                }
				return managed.Value;
            }
        }
    }
}
